import { getUserProfile } from '@/api'
import { defineStore } from 'pinia'

const id = 'user'

const store = defineStore(id, {
  state: () => ({
    token: '',
    is_root: false,
    roles: [] as string[],
    permissions: [] as string[],
    // 是否已注册路由，不能持久化，刷新页面需要重新添加路由
    isAddRouter: false
  }),
  getters: {
    access(state) {
      return state.permissions.reduce(
        (acc: Record<string, boolean>, permission) => ((acc[permission] = true), acc),
        {}
      )
    }
  },
  actions: {
    async login() {
      const { is_root, roles, permissions } = await getUserProfile()
      this.is_root = is_root
      this.roles = roles
      this.permissions = permissions
    },
    isLogin() {
      return !!this.token
    }
  },
  persist: {
    key: id,
    // 需要持久化存储的 key
    paths: ['token', 'is_root', 'roles', 'permissions']
  }
})

export default store
